import React, { useState, useEffect } from 'react'
import './index.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useDebounceFn } from 'ahooks'
import { get } from 'lodash'
import { getBtnStatus, projectId } from '@/utils/constants'
import { addToast } from '@/components/common/Toast/toast.module'
import { toSettleAccounts } from '@/utils/jumpSettleAccounts'
import { reportClick } from '@/utils/ping'
import CountdownComponent from './CountdownComponent'
import { isJDAPP } from '@/utils/navigation'

export default (props) => {
	const top = useSelector((state) => state.top)
	const [scrollFlag, setScrollFlag] = useState(true)
	const redoundItemData = useSelector((state) => state.redoundItemData)
	const { redoundItem, count, selected } = redoundItemData
	const supportRedoundId = redoundItem.redoundId

	const dispatch = useDispatch()
	const dialogData = useSelector((state) => state.dialogData)
	const homeData = useSelector((state) => state.homeData)
	const reminderStatus = useSelector((state) => state.reminderStatus)
	const storyPageData = get(homeData, 'storyPageData', {})
	const projectStoryNewDto = get(storyPageData, 'projectStoryNewDto', {})
	const buttonStatus = get(projectStoryNewDto, 'buttonStatus', 0)
	const isOpen = get(dialogData, 'isOpen', false)

	// 页面主按钮
	const [buttonObj, setButtonObj] = useState({
		image: '',
		event: '',
	})
	useEffect(() => {
		/**
		 * 根据弹窗是否弹起确定按钮及状态
		 * 如果弹窗唤起，则根据选择档位等信息确定按钮状态
		 * 否则根据主接口字段确定按钮状态
		 */
		if (isOpen) {
			if (!redoundItem.canBuy) {
				// 判断是否可购买 如果不可即为已售完
				setButtonObj({
					image:
						'https://img12.360buyimg.com/imagetools/jfs/t1/139324/11/13425/11505/5fa3c302E10691891/086a54507dc19144.png',
					event() {},
				})
				return
			}
			if (selected) {
				// 判断是否有选中的
				if (count > redoundItem.limits) {
					// 如果用户选择值大于库存数或者单个用户可选择上限，则toast提示
					// TODO
					setButtonObj({
						image:
							'https://img14.360buyimg.com/imagetools/jfs/t1/129021/20/17538/12871/5fa3c302E4c1a7aca/dfcc42e5eb539c22.png',
						event() {
							dispatch(addToast(`库存不足，请减少购买数量`))
						},
					})
					return
				}
				if (count > redoundItem.supportLimit) {
					// 如果用户选择值大于支持数量上限，则toast提示
					// TODO
					setButtonObj({
						image:
							'https://img14.360buyimg.com/imagetools/jfs/t1/129021/20/17538/12871/5fa3c302E4c1a7aca/dfcc42e5eb539c22.png',
						event() {
							dispatch(addToast(`超出购买上限，请减少购买数量`))
						},
					})
					return
				}
				if (count <= redoundItem.limits) {
					// 如果用户选择值小于库存数，可跳转
					if (supportRedoundId === '') {
						// 如果选择档位id为空  toast提示
						setButtonObj({
							image:
								'https://img14.360buyimg.com/imagetools/jfs/t1/129021/20/17538/12871/5fa3c302E4c1a7aca/dfcc42e5eb539c22.png',
							event() {
								dispatch(addToast('请选择其他档位'))
							},
						})
						return
					}
					// 判断是否选择档位
					setButtonObj({
						image:
							'https://img14.360buyimg.com/imagetools/jfs/t1/129021/20/17538/12871/5fa3c302E4c1a7aca/dfcc42e5eb539c22.png',
						event() {
							reportClick({
								eventId: 'Mhelp_StoryDetail_MianbanSupportRightnow',
								eventParam: `${projectId}_${buttonStatus}_${supportRedoundId}_${count}`,
							})
							// if (isJDAPP) {
							toSettleAccounts({
								supnum: count,
								projectId,
								// 如果为打赏类型 redoundId 传0
								redoundId: supportRedoundId,
							})
							// } else {
							// 	dispatch(addToast('请前往app下单'))
							// }
						},
					})
				}
			} else if (!selected) {
				// 无选中的提示用户选择档位
				setButtonObj({
					image:
						'https://img14.360buyimg.com/imagetools/jfs/t1/129021/20/17538/12871/5fa3c302E4c1a7aca/dfcc42e5eb539c22.png',
					event() {
						dispatch(addToast('请选择档位'))
					},
				})
			}
		} else {
			setButtonObj(getBtnStatus(buttonStatus, reminderStatus))
		}
		return () => {}
	}, [dialogData, homeData, reminderStatus, redoundItemData, selected])

	/**
	 * 获取tips展示字段
	 */
	const salesTime = get(projectStoryNewDto, 'salesTime', 0)
	const endTime = get(projectStoryNewDto, 'endTime', 0)
	const systemTime = get(projectStoryNewDto, 'systemTime', 0)
	const timeGTAOneDay = salesTime - systemTime > 60000 * 24 * 60
	const date = new Date(endTime)
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const show = useDebounceFn(
		() => {
			setScrollFlag(false)
		},
		{
			wait: 200,
		}
	)
	const hide = useDebounceFn(
		() => {
			setScrollFlag(true)
		},
		{
			wait: 10,
		}
	)

	useEffect(() => {
		hide.run()
		show.run()
		return () => {
			show.cancel()
			hide.cancel()
		}
	}, [top])
	const handleClick = () => {
		if (isOpen) {
			buttonObj.event()
		} else {
			// 去预约或者立即支持
			if (buttonObj.event) {
				if (buttonObj.event.type === 'open:dialog') {
					reportClick({
						eventId: 'Mhelp_StoryDetail_BottomSupportRightnow',
						eventParam: `${projectId}`,
					})
				}
				dispatch(buttonObj.event)
			}
		}
	}

	const timeChange = () => {
		// 倒计时结束刷新页面
		dispatch({ type: 'reload:homeData' })
	}
	return (
		<div
			className={`bottom-btn-back ${scrollFlag ? 'hide-bottom-modal' : 'show-bottom-modal'}`}>
			<div className="btn-word">
				{buttonStatus === 1 && timeGTAOneDay ? (
					<CountdownComponent
						systemTime={systemTime}
						salesTime={salesTime}
						tpl={`将于<span class="d">{{d}}</span>天<span class="h">{{h}}</span>小时后开始`}
					/>
				) : null}
				{buttonStatus === 1 && !timeGTAOneDay ? (
					<CountdownComponent
						systemTime={systemTime}
						salesTime={salesTime}
						tpl={`将于<span class="h">{{h}}</span>:<span class="m">{{m}}</span>:<span class="s">{{s}}</span>后开始`}
					/>
				) : null}
				{buttonStatus === 3 ? (
					<div className="word-bg">
						<div className="word">
							{`	已于
							${year}年${month}月${day}
							日众筹成功`}
						</div>
					</div>
				) : null}
				{buttonStatus === 4 ? (
					<div className="word-bg">
						<div className="word">
							{`已于
							${year}年${month}月${day}
							结束，众筹失败`}
						</div>
						<div className="word-icon" />
					</div>
				) : null}
			</div>
			<div
				className="bottom-btn"
				style={{
					backgroundImage: `url(${buttonObj.image})`,
					backgroundSize: '100% 100%',
					backgroundRepeat: 'no-repeat',
				}}>
				<div className="btn-area" onClick={handleClick}></div>
			</div>
		</div>
	)
}
